from urllib import urlopen
from xml.dom.minidom import parseString



class OSMMapDataRequest:
    def __init__(self,lat1,lon1,lat2,lon2):
        self.lat1 = lat1
        self.lat2 = lat2
        self.lon1 = lon1
        self.lon2 = lon2

class OSMService:
    def __init__(self):
        pass
    
    def getMapData(self,request):
        dataUrl = "http://api.openstreetmap.org/api/0.6/map?bbox=%s,%s,%s,%s" % (request.lon1,request.lat1,request.lon2,request.lat2)
        f = urlopen(dataUrl)
        data = f.read()
        #logging.debug("got data from osm (%s): %s" % (dataUrl,data.encode("utf-8")))
        f.close()
        return  self.parseMapData(unicode( data, "utf-8" )) 
    
    def parseMapData(self,data):
        """
            return format:
            [{"name","lat","lon","tags":{}}]
        """
        def collapseTags2Dict(n):
            ts = {}
            tags = n.getElementsByTagName("tag")
            for t in tags:
                ts[t.getAttribute("k")] = t.getAttribute("v")
            return ts
        
        def reduceTagsDict(d):
            ks = ["tourism","historic","natural","sport","wikipedia","leisure","shop","name"]
            rd = {}
            for k,v in d.items():
                if k in ks: rd[k]=v
            return rd
        
        results = []
        
        doc = parseString(data.encode("utf-8"))
        nodes = doc.getElementsByTagName("node")
        for node in nodes:
            tags = node.getElementsByTagName("tag")
            if len(tags) == 0: continue    
            
            tags = reduceTagsDict(collapseTags2Dict(node))
            
            if len(tags.items()) == 0: continue
            if not tags.has_key("name"): continue
            if len(tags.items()) == 1: continue
            
            name = tags["name"]
            del tags["name"]
            newSpot = {
                       "name":name,
                       "lat":node.getAttribute("lat"),
                       "lon":node.getAttribute("lon"),
                       "tags": tags,
                       "osmId":node.getAttribute("id")
                       }
            
            results.append(newSpot)
            
        return results  